package pikes.xml;

import java.io.IOException;
import java.io.StringWriter;

/**
 * Abstract markup which implements the print and toString methods. When calling {@link #print(Appendable)}, visit is
 * called with an XMLWriter instance.<br>
 * When calling {@link #toString()}, print is called with an StringWriter instance.
 * @author Peter Bona
 * @see pikes.xml.XMLWriter
 * @see java.io.StringWriter
 */
public abstract class PrintableXMLMarkup implements XMLMarkup {

	/**
	 * Calls visit method with XMLWriter as parameter.
	 * @param appendable character stream
	 * @throws IOException
	 */
	public final void print(Appendable appendable) throws IOException {
		XMLVisitor xmlWriter = new XMLWriter(appendable);
		try {
			visit(xmlWriter);
		}
		catch (Exception e) {
			throw new IOException(e.getMessage());
		}
	}

	/**
	 * Calls print method with StringWriter as parameter. If an exception is thrown, empty string is returned.
	 */
	@Override
	public String toString() {
		StringWriter writer = new StringWriter();
		try {
			print(writer);
		}
		catch (Exception e) {
			return "";
		}
		writer.flush();
		return writer.toString();
	}
}
